package cn.bincker.mybatis.encrypt.converter.impl;

import cn.bincker.mybatis.encrypt.exception.MybatisEncryptException;

import javax.sql.rowset.serial.SerialClob;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.sql.Clob;
import java.sql.SQLException;

public class ClobConverter extends BaseEncryptConverter<Clob> {
    @Override
    Clob convertNonNull(byte[] data) {
        try {
            return new SerialClob(StandardCharsets.UTF_8.decode(ByteBuffer.wrap(data)).array());
        } catch (SQLException e) {
            throw new MybatisEncryptException(e);
        }
    }

    @Override
    byte[] convertNonNull(Clob object) {
        try(
                var out = new ByteArrayOutputStream();
                var writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                var reader = object.getCharacterStream()
        ) {
            reader.transferTo(writer);
            writer.flush();
            return out.toByteArray();
        } catch (IOException | SQLException e) {
            throw new MybatisEncryptException(e);
        }
    }
}
